#
# fusion.http.util
#
# Copyright 2007 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Ken Rimey <rimey@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import cgi
import urlparse
from cStringIO import StringIO
from xml.etree.ElementTree import Element, tostring

import web              # http://webpy.org/

from fusion.http.server import MAIN, ADMIN

def withdb(method):
    def wrapper(self, *args):
        db = web.config.DB()
        try:
            method(self, db, *args)
        finally:
            db.close()

    return wrapper

def format_xml(tag, text=None, **attributes):
    xml = Element(tag, **attributes)
    xml.text = text
    return tostring(xml)

def created(url=''):
    url = urlparse.urljoin(web.ctx.home + web.ctx.path, url)
    web.ctx.status = '201 Created'
    web.ctx.output = ''    
    web.header('Content-Type', 'text/html') # XXX Needed?
    web.header('Location', url)

def unauthorized():
    web.ctx.status = '401 Unauthorized'
    web.header('Content-Type', 'text/plain')
    return web.output('unauthorized')

def read_form():
    return cgi.FieldStorage(
        keep_blank_values = True,
        fp = StringIO(web.data()),
        environ = web.ctx.env.copy())

def get_fields(form, name):
    return form[name] if isinstance(form[name], list) else [form[name]]

def authorized_referer(collection=None):
    # The admin port could be locked down further using standard
    # techniques, but referrer checks are the best we can do in
    # isolating collections from each other for writing.  That is
    # because we serve all collections from the main port and thus
    # cannot keep per-collection secrets (since the browser's Same
    # Origin Policy doesn't come into effect in that case).

    referer = web.ctx.env.get('HTTP_REFERER')
    if not referer:
        return False

    if referer.startswith(ADMIN + '/'):
            return True

    if collection:
        url = MAIN + '/collection/' + collection
        if referer.startswith(url):
            return True

        url = MAIN + '/profile/' + collection
        if referer.startswith(url):
            return True

    return False
